<?php


namespace app\backstage\logic;


use app\backstage\model\ManagerUser;
use app\backstage\model\QuickAppToManagerAccess;
use app\common\classes\BehaviorRedis;
use app\common\model\Novel;
use app\common\model\NovelChapter;
use app\common\model\NovelCustom;
use app\common\model\NovelToAgentAccess;
use app\common\model\NovelToLabelAccess;
use app\common\model\QuickApp;
use app\common\model\QuickLink;
use think\Db;

class SpreadLogic
{

    /**
     * 推广书籍列表
     * @param $where
     * @param $page
     * @param $limit
     * @return array
     * @Author: whh
     */
    public function getNovelList($where, $page, $limit)
    {
        $orderBy = "id desc";
        $novelModel = new Novel();
        $role = request()->_role;
        $user = request()->_user;
        $where[] = ['in_shelf', '=', 1];//上架
        $query = $novelModel->where($where)->where(function ($query) use ($role, $user) {
            /**
             * 专属书籍
             */
            if ($role->alias == 'agent' || $role->alias == 'channel') {
                if ($role->alias == 'channel') {
                    $novelIds = NovelToAgentAccess::where("agent_id", $user->parent_id)->column('nid');
                } else {
                    $novelIds = NovelToAgentAccess::where("agent_id", $user->id)->column('nid');
                }
                $query->where('is_exclusive', 0)
                    ->whereOr('id', 'in', $novelIds);
            }
        });
        $count = $query->count();
        $list = $query->page($page, $limit)->with(['freq', 'novel_class'])->order($orderBy)->select();

        foreach ($list as $k => $v) {
            //查询默认收费章节
            $list[$k]['first_pay'] = NovelChapter::where("novel_id", $v->id)->where("is_pay", 1)->min('chapter_no');
            $linkWhere = [];
            $linkWhere[] = ['novel_id', '=', $v->id];
            if ($role->alias == 'channel') {
                $linkWhere[] = ['channel_id', '=', $user->id];
            }
            if ($role->alias == 'agent') {
                $linkWhere[] = ['agent_id', '=', $user->id];
            }
            if ($role->alias == 'eb') {
                $sonIds = ManagerUser::where("parent_id", $user->id)->column('id');
                $linkWhere[] = ['agent_id', 'in', $sonIds];
            }

            $list[$k]['charging_section'] = Db::table('novel_chapter')->where('novel_id',$v->id)->where('is_pay',1)
                            ->order('chapter_no ASC')->value('chapter_no');

            $list[$k]['linkCount'] = QuickLink::where($linkWhere)->count();
        }
        return ['list' => $list, 'count' => $count];
    }

    /**
     * 设置连接
     * @param $params
     * @param int $id
     * @return \think\response\Json
     */
    public function setLink($params, $id = 0)
    {
        /*if ($params['quick_id'] != 3){
            return errJson('此时间段暂停提取链接');
        }*/
        $role = request()->_role;
        $user = request()->_user;
        $novel = Novel::where('id', $params['novel_id'])->where(function ($query) use ($role, $user, $id) {
            /**专属书籍*/
            if (!$id) {
                if ($role->alias == 'agent' || $role->alias == 'channel') {
                    if ($role->alias == 'channel') {
                        $novelIds = NovelToAgentAccess::where("agent_id", $user->parent_id)->column('nid');
                    } else {
                        $novelIds = NovelToAgentAccess::where("agent_id", $user->id)->column('nid');
                    }
                    $query->where('is_exclusive', 0)
                        ->whereOr('id', 'in', $novelIds);
                }
            }
        })->find();
        if (!$novel) return errJson('小说不可用');
        if ($params['force_switch'] == 1) {
            /**
             * 判断是否强加桌，判断章节
             */
            $chapter[] = ['novel_id', '=', $novel->id];
            if (isset($params['force_chapter_no']) && $params['force_chapter_no']) {
                $chapter[] = ['chapter_no', '=', $params['force_chapter_no']];
                $forceChapter = NovelChapter::where($chapter)->find();
                if (!$forceChapter) {
                    return errJson('请设置正确的强加桌章节');
                }
            } else {
                $params['force_chapter_no'] = $params['chapter_no'];
            }
            if ($params['force_chapter_no'] < $params['chapter_no']) {
                return errJson('强加桌章节序号必须>=入口章节序号');
            }
        }
        if (!isset($params['chapter_words_fee']) || !$params['chapter_words_fee']) {
            $chapter_words_fee = $novel->words_fee;
        } else {
            $chapter_words_fee = $params['chapter_words_fee'];
        }
        if (!$id) {
            if ($role->alias != 'channel') {
                return errJson('只有投放号角色才能创建链接，请登录投放号账号！');
            }
            //判断此App是否授权
            $qa = QuickApp::get($params['quick_id']);
            if (!$qa) {
                return errJson('App不存在');
            }
            $have = QuickAppToManagerAccess::where('uid', $user->id)->where('quick_id', $params['quick_id'])->find();
            if (!$have) {
                return errJson('App未授权');
            }
            $token = $this->make_token();
            $res = [
                'hap_link' => "hap://app/{$qa->package_name}/pages/read?token={$token}",
                'hapjs_link' => "https://hapjs.org/app/{$qa->package_name}/pages/read?token={$token}",
            ];
            $save = [
                'name' => $params['name'],
                'token' => $token,
                'route' => '/pages/read',
                'quick_id' => $params['quick_id'],
                'agent_id' => $user->parent_id,
                'channel_id' => $user->id,
                'novel_id' => $novel->id,
                'chapter_no' => $params['chapter_no'],
                'hap_link' => $res['hap_link'],
                'hapjs_link' => $res['hapjs_link'],
                'enter_pop' => $params['enter_pop'],
                'force_switch' => $params['force_switch'],
                'force_chapter_no' => $params['force_switch'] == 1 ? $params['force_chapter_no'] : 0,
                'chapter_words_fee' => $chapter_words_fee,
                'template_id' => $params['template_id'],
            ];
            $field = ['name', 'token', 'route', 'quick_id', 'agent_id', 'channel_id', 'novel_id',
                'chapter_no', 'cost', 'hap_link', 'hapjs_link', 'enter_pop', 'force_switch', 'force_chapter_no', 'template_id', 'chapter_words_fee'];
            $ql = new QuickLink();
            $ql->allowField($field)->save($save);
            return sucJson($res);
        } else {
            $save = [
                'name' => $params['name'],
                'chapter_no' => $params['chapter_no'],
                'enter_pop' => $params['enter_pop'],
                'force_switch' => $params['force_switch'],
                'force_chapter_no' => $params['force_switch'] == 1 ? $params['force_chapter_no'] : 0,
                'chapter_words_fee' => $chapter_words_fee,
                'template_id' => $params['template_id'],
                'push_link' => $params['push_link'],
            ];
            QuickLink::where("id", $id)->update($save);
            return sucJson();
        }
    }


    /**
     * 制作Token
     * @return string
     */
    public function make_token()
    {
        $code = 'ABCDEFGHIJKLMNOPQRSTUVWXYZ';
        $rand = $code[rand(0, 25)]
            . strtoupper(dechex(date('m')))
            . date('d') . substr(time(), -5)
            . substr(microtime(), 2, 5)
            . sprintf('%02d', rand(0, 99));
        for (
            $a = md5($rand, true),
            $s = '0123456789ABCDEFGHIJKLMNOPQRSTUV',
            $d = '',
            $f = 0;
            $f < 8;
            $g = ord($a[$f]),
            $d .= $s[($g ^ ord($a[$f + 8])) - $g & 0x1F],
            $f++
        ) ;
        return $d;
    }

    /**
     * 链接列表
     * @param $where
     * @param $page
     * @param $limit
     * @return mixed
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function linkList($where, $page, $limit)
    {
        $orderBy = "id desc";
        $list = QuickLink::getList($where, '*', $orderBy, $page, $limit, ['quick_app', 'agent', 'channel', 'novel'])->toArray();
        $linkIds = array_column($list, 'id');
        $rpField = "sum(new_fan_num) new_fan_num,sum(jiazhuo_num) jiazhuo_num,sum(recharge_money) recharge_money,sum(click_uv) click_uv, sum(recharge_count) recharge_count";
        $yesterday = date("Y-m-d", strtotime("-1 day"));
        $today = date("Y-m-d");
        /**历史*/
        $rpWhere[] = ['report_date', "<", $yesterday];
        $rpWhere[] = ['link_id', "in", $linkIds];
        $dateDaily = Db::table("rp_link_daily")->where($rpWhere)->group("link_id")->column($rpField, "link_id");

        /**两天内实时*/
        //注册
        $regWhere[] = ['regdate', 'in', [$yesterday, $today]];
        $regWhere[] = ['source_link_id', 'in', $linkIds];
        $newFanNumList = Db::table("quick_user")->field("count(*) new_fan_num,link_id")->where($regWhere)->group("link_id")->select();
        $newFanNumList = array_column($newFanNumList, null, 'link_id');

        //加桌
        $addWhere[] = ['create_date', 'in', [$yesterday, $today]];
        $addWhere[] = ['link_id', 'in', $linkIds];
        $jiazhuoNumList = Db::table("quick_user_add_shortcut")->field("count(*) jiazhuo_num,link_id")->where($addWhere)->group("link_id")->select();
        $jiazhuoNumList = array_column($jiazhuoNumList, null, 'link_id');

        //充值
        $moneyWhere[] = ['create_date', 'in', [$yesterday, $today]];
        $moneyWhere[] = ['link_id', 'in', $linkIds];
        $moneyWhere[] = ['status', '=', 2];
        $moneyList = Db::table("pay_order")->field("sum(total_fee) recharge_money,link_id")->where($moneyWhere)->group("link_id")->select();
        $moneyList = array_column($moneyList, null, 'link_id');
        $rCountList = Db::table("pay_order")->field("count(*) recharge_count,link_id")->where($moneyWhere)->group("link_id")->select();
        $rCountList = array_column($rCountList, null, 'link_id');

        $redis = new BehaviorRedis();
        $h5Link = config('api_domain')."/link/open?token=";
        foreach ($list as $k => $v) {
            $list[$k]['h5Link'] = $h5Link.$v['token'];
            $new_fan_num = 0;
            $jiazhuo_num = 0;
            $rechargeMoney = 0;
            $rechargeCount = 0;

            $click_uv = $recharge_count_history = 0;
            if (isset($dateDaily[$v['id']])) {
                $new_fan_num = $dateDaily[$v['id']]['new_fan_num'];
                $jiazhuo_num = $dateDaily[$v['id']]['jiazhuo_num'];
                $rechargeMoney = $dateDaily[$v['id']]['recharge_money'];
                $click_uv = $dateDaily[$v['id']]['click_uv'];
                $recharge_count_history = $dateDaily[$v['id']]['recharge_count'];
            }
            if (isset($newFanNumList[$v['id']])) {
                $new_fan_num += $newFanNumList[$v['id']]['new_fan_num'];
            }
            if (isset($jiazhuoNumList[$v['id']])) {
                $jiazhuo_num += $jiazhuoNumList[$v['id']]['jiazhuo_num'];
            }
            if (isset($moneyList[$v['id']])) {
                $rechargeMoney += $moneyList[$v['id']]['recharge_money'];
            }

            if (isset($rCountList[$v['id']])) {
                $rechargeCount += $rCountList[$v['id']]['recharge_count'];
            }
            $list[$k]['new_fan_num'] = $new_fan_num;
            $list[$k]['jiazhuo_num'] = $jiazhuo_num;
            $list[$k]['recharge_money'] = moneyFormat($rechargeMoney);
            $list[$k]['recharge_count'] = $rechargeCount + $recharge_count_history;
            $list[$k]['click_uv'] = $click_uv + $redis->getLinkUvCount($v['id'], $today) + $redis->getLinkUvCount($v['id'], $yesterday);

            $list[$k]['new_fan_ratio'] = $list[$k]['click_uv'] > 0 ? round($new_fan_num / $list[$k]['click_uv'] * 100, 2) : 0;//新用户占比
            $list[$k]['jiazhuo_ratio'] = $list[$k]['new_fan_num'] > 0 ? round($jiazhuo_num / $list[$k]['new_fan_num'] * 100, 2) : 0;//加桌率
            $list[$k]['return_rate'] = $list[$k]['cost'] > 0 ? round(($rechargeMoney / 100) / $list[$k]['cost'] * 100, 2) : 0;//回本率

        }
        return $list;
    }

    /**
     * 链接日期
     * @param $linkId
     * @param $date
     * @return mixed
     */
    public function linkDateData($linkId, $date)
    {
        $redis = new BehaviorRedis();
        $data['new_fan_num'] = Db::table("quick_user")->where("regdate", $date)->where("source_link_id", $linkId)->count();//新粉数
        $data['jiazhuo_num'] = Db::table("quick_user_add_shortcut")->where("create_date", $date)->where("link_id", $linkId)->count();//加桌数
        $data['recharge_money'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->where("status", 2)->sum('total_fee') ?? 0;//充值金额
        $data['recharge_count'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->where("status", 2)->count();//充值次数
        $data['lift_count'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->count();//起吊次数
        $data['lift_uv'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->group('uid')->count();//起吊人数
        $data['pay_uv'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->where("status", 2)->group('uid')->count();//充值人数
        $data['new_user_money'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->where("status", 2)->where("user_reg_date", $date)->sum('total_fee') ?? 0;//新用户充值
        $data['new_pay_num'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->where("status", 2)->where("user_reg_date", $date)->group('uid')->count();//新用户充值人数
        $data['new_pay_count'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->where("status", 2)->where("user_reg_date", $date)->count();//新用户充值笔数
        $data['new_gs_money'] = Db::table("pay_order")->where("create_date", $date)->where("link_id", $linkId)->where("status", 2)->where("user_source_date", $date)->sum('total_fee') ?? 0;//新归属用户充值

        $data['click_uv'] = $redis->getLinkUvCount($linkId, $date);//点击人数

        $data['new_fan_ratio'] = $data['click_uv'] > 0 ? round($data['new_fan_num'] / $data['click_uv'] * 100, 2) : 0;//新用户占比
        $data['jiazhuo_ratio'] = $data['new_fan_num'] > 0 ? round($data['jiazhuo_num'] / $data['new_fan_num'] * 100, 2) : 0;//加桌率
        $data['ffcg_ratio'] = $data['lift_count'] > 0 ? round($data['recharge_count'] / $data['lift_count'] * 100, 2) : 0;//付费成功率
        $data['newmoney_ratio'] = $data['recharge_money'] > 0 ? round($data['new_user_money'] / $data['recharge_money'] * 100, 2) : 0;//新用户充值占比
        $data['new_pay_ratio'] = $data['new_fan_num'] > 0 ? round($data['new_pay_num'] / $data['new_fan_num'] * 100, 2) : 0;//新用户付费率
        $data['rj_money'] = $data['pay_uv'] > 0 ? round($data['recharge_money'] / $data['pay_uv'], 2) : 0;//人均充值金额
        $data['newgs_ratio'] = $data['recharge_money'] > 0 ? round($data['new_gs_money'] / $data['recharge_money'] * 100, 2) : 0;//新归属用户充值占比


        $data['recharge_money'] = round($data['recharge_money'] / 100, 2);
        $data['new_user_money'] = round($data['new_user_money'] / 100, 2);
        $data['rj_money'] = round($data['rj_money'] / 100, 2);
        $data['new_gs_money'] = round($data['new_gs_money'] / 100, 2);
        return $data;
    }

    /**
     * 链接明细
     * @param $where
     * @param $page
     * @param $limit
     * @return \think\response\Json
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\ModelNotFoundException
     * @throws \think\exception\DbException
     */
    public function linkDaily($where, $page, $limit)
    {
        $list = Db::table("rp_link_daily")->where($where)->page($page, $limit)->order("report_date desc")->select();
        $count = Db::table("rp_link_daily")->where($where)->count();
        foreach ($list as $k => $v) {
            $list[$k]['new_fan_ratio'] = $list[$k]['click_uv'] > 0 ? round($list[$k]['new_fan_num'] / $list[$k]['click_uv'] * 100, 2) : 0;//新用户占比
            $list[$k]['jiazhuo_ratio'] = $list[$k]['new_fan_num'] > 0 ? round($list[$k]['jiazhuo_num'] / $list[$k]['new_fan_num'] * 100, 2) : 0;//加桌率
            $list[$k]['ffcg_ratio'] = $list[$k]['lift_count'] > 0 ? round($list[$k]['recharge_count'] / $list[$k]['lift_count'] * 100, 2) : 0;//付费成功率

            $list[$k]['newmoney_ratio'] = $list[$k]['recharge_money'] > 0 ? round($v['new_user_money'] / $list[$k]['recharge_money'] * 100, 2) : 0;//新用户充值占比
            $list[$k]['new_pay_ratio'] = $list[$k]['new_fan_num'] > 0 ? round($list[$k]['new_pay_num'] / $list[$k]['new_fan_num'] * 100, 2) : 0;//新用户付费率
            $list[$k]['rj_money'] = $list[$k]['pay_uv'] > 0 ? round($list[$k]['recharge_money'] / $list[$k]['pay_uv'], 2) : 0;//人均充值金额
            $list[$k]['newgs_ratio'] = $list[$k]['recharge_money'] > 0 ? round($v['new_gs_money'] / $list[$k]['recharge_money'] * 100, 2) : 0;//新归属用户充值占比


            $list[$k]['recharge_money'] = round($v['recharge_money'] / 100, 2);
            $list[$k]['new_user_money'] = round($v['new_user_money'] / 100, 2);
            $list[$k]['rj_money'] = round($list[$k]['rj_money'] / 100, 2);
            $list[$k]['new_gs_money'] = round($v['new_gs_money'] / 100, 2);
        }

        return sucJson($list, $count);
    }
}